package com.algorithm.liyc.echa;

import com.algorithm.liyc.entity.TreeNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 101. 对称二叉树
 * 给定一个二叉树，检查它是否是镜像对称的。
 *
 * @author Liyc
 * @date 2023/12/28 17:00
 **/

public class Solution6 {
    /**
     * 递归法
     * @param root
     * @return
     */
    public boolean isSymmetric1(TreeNode root) {
        if (root == null) return false;
        return compare(root.left, root.right);
    }
    public boolean compare(TreeNode left, TreeNode right) {
        if (left == null && right != null) {
            return false;
        }
        if (left != null && right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        if (left == null && right == null) {
            return true;
        }
        boolean precompare = compare(left.left, right.right);
        boolean postcompare = compare(left.right, right.left);
        return precompare && postcompare;
    }

    /**
     * 迭代法
     * 使用双端队列，相当于两个栈
     * @param root
     * @return
     */
    public boolean isSymmetric2(TreeNode root) {
        if (root == null) return false;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerFirst(root.left);
        deque.offerLast(root.right);
        while (!deque.isEmpty()) {
            TreeNode left = deque.pollFirst();
            TreeNode right = deque.pollLast();
            if (left == null && right != null) {
                return false;
            }
            if (left != null && right == null) {
                return false;
            }
            if (left.val != right.val) {
                return false;
            }
            if (left == null && right == null) {
                continue;
            }
            deque.offerFirst(left.left);
            deque.offerFirst(left.right);
            deque.offerLast(right.right);
            deque.offerLast(right.left);

        }
        return true;
    }

    /**
     * 迭代法
     * 使用普通队列
     * @param root
     * @return
     */
    public boolean isSymmetric3(TreeNode root) {
        if (root == null) return false;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);
        while (!queue.isEmpty()) {
            TreeNode left = queue.poll();
            TreeNode right = queue.poll();
            if (left == null && right != null) {
                return false;
            }
            if (left != null && right == null) {
                return false;
            }
            if (left.val != right.val) {
                return false;
            }
            if (left == null && right == null) {
                continue;
            }
            queue.offer(left.left);
            queue.offer(right.right);
            queue.offer(left.right);
            queue.offer(right.left);
        }
        return true;
    }
}
